export default {
  set(key, obj) {
    return new Promise(resolve => {
      uni.setStorage({
        key,
        data: JSON.stringify(obj),
        success: resolve
      })
    })
  },
  getSync(key, def = null) {
    const data = uni.getStorageSync(key)
    if(data) {
      try {
        return JSON.parse(data)
      } catch (e) {
        console.log(key, e)
        return data
      }
    }

    return def
  },
  get(key, def = null) {
    return new Promise(resolve => {
      uni.getStorage({
        key,
        success: (data) => {
          // console.log(data.data, 'data.data')
          if (data.data) {
            try {
              resolve(JSON.parse(data.data))
            } catch (e) {
              console.log(key, e)
              resolve(data.data)
            }
          } else {
            resolve(null)
          }
        },
        fail: () => {
          console.log('empty', key)
          resolve(def)
        }
      })
    })
  },
  del(key) {
    return new Promise(resolve => {
      uni.removeStorage({
        key,
        complete: () => {
          resolve()
        }
      })
    })
  }
}
